package com.tale.init;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blade.mvc.Const;




/**
 * SQLite 数据库操作
 * <p>
 * Created by smallcc on 2017/3/4.
 */


public final class SqliteJdbc {
	private SqliteJdbc() {}
	private static final Logger log = LoggerFactory.getLogger(SqliteJdbc.class);
	public static final String DB_NAME = "tale.db";
	public static String dbPath;
	public static String dbSrc;
	private static final String PATH = "/";

	static {
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (Exception e) {
			log.error("load sqlite driver error", e);
		}
	}

	/**
	 * 测试连接并导入数据库
	 */
	public static void importSql(boolean devMode) {
		dbPath = Const.CLASSPATH + File.separatorChar + DB_NAME;
		dbSrc = "jdbc:sqlite://" + dbPath;

		if (devMode) {
			dbPath = System.getProperty("user.dir") + PATH + DB_NAME;
			dbSrc = "jdbc:sqlite://" + dbPath;
		}

		log.info("blade dev mode: {}", devMode);
		log.info("load sqlite database path [{}]", dbPath);
		log.info("load sqlite database src [{}]", dbSrc);
		String querySql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='t_options'";
		String cp = SqliteJdbc.class.getClassLoader().getResource("").getPath();
		try (Connection con = DriverManager.getConnection(dbSrc);
				Statement statement = con.createStatement();
				ResultSet rs = statement.executeQuery(querySql);
				InputStreamReader isr = new InputStreamReader(new FileInputStream(cp + "schema.sql"), StandardCharsets.UTF_8)){
			int count = rs.getInt(1);
			if (count == 0) {
				String sql = new BufferedReader(isr).lines().collect(Collectors.joining("\n"));
				int r = statement.executeUpdate(sql);
				log.info("initialize import database - {}", r);
			}
			log.info("database path is: {}", dbPath);
		} catch (Exception e) {
			log.error("initialize database fail", e);
		}
	}

}